# -*- coding: utf-8 -*-
import json
import scrapy
from scrapy import Request
from zc_core.model.items import Box
from gd_collection.rules import *
from scrapy.utils.project import get_project_settings
from zc_core.spiders.base import BaseSpider


class SkuSpider(BaseSpider):
    name = 'spu'
    # 集采管分类链接
    index_url = 'https://gdgpo.czt.gd.gov.cn/gpmall-basic/api/index/v1/getGoodsClassIndex'
    # 商品列表页 post
    sku_list_url = 'https://gdgpo.czt.gd.gov.cn/gpmall-goodslibrary-interface/api/goodsPrice/v1/goodsPriceList'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(SkuSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        self.page_size = 20
        self.settings = get_project_settings()

    def _build_list_req(self, url, catalog3Id, page):
        return scrapy.Request(
            method='POST',
            url=url,
            meta={
                'reqType': 'sku',
                'batchNo': self.batch_no,
                'catalog3Id': catalog3Id,
                'page': page,
            },
            body=json.dumps({"categoryguid": catalog3Id, "pageno": page, "goodsbrandguid": "",
                             "goodsbrandname": "", "goodsclassguid": "", "paraminfos": "[]",
                             "orderinfos": json.dumps({"sorttype": "currentprice", "orderrole": "up"}),
                             "pricelower": "",
                             "priceup": "", "regionguid": "2137001", "goodssource": "", "keyword": "",
                             "platform": "1"}),
            headers={
                'Content-Type': 'application/json;charset=UTF-8',
            },
            callback=self.parse_sku_content_deal,
            errback=self.error_back,
            dont_filter=True
        )

    def start_requests(self):
        # 品类、品牌
        yield Request(
            method='POST',
            url=self.index_url,
            meta={
                'reqType': 'sku',
                'batchNo': self.batch_no,
            },
            body=json.dumps({"regionGuid": "2137001", "platform": "1"}),
            headers={'Content-Type': 'application/json;charset=UTF-8'},
            callback=self.parse_catalog,
            errback=self.error_back,
            dont_filter=True,
        )

    # 处理sku列表
    def parse_catalog(self, response):
        # 处理品类列表
        cats = parse_catalog(response)
        if cats:
            self.logger.info('品类: count[%s]' % len(cats))
            yield Box('catalog', self.batch_no, cats)
            for cat in cats:
                if cat.get('level') == 3:
                    # 采集sku列表
                    catalog3Name = cat.get('catalogName')
                    catalog3Id = cat.get('catalogId')
                    # if catalog3Name in ['液晶显示器']:
                    yield self._build_list_req(self.sku_list_url, catalog3Id, 1)

    # 处理sku列表
    def parse_sku_content_deal(self, response):
        meta = response.meta
        catalog3Id = meta.get('catalog3Id')
        cur_page = meta.get('page')
        # 处理spu列表
        spu_list = parse_spu(response)
        self.logger.info("清单: cat=%s, page=%s" % (catalog3Id, cur_page))
        if spu_list:
            yield Box('spu', self.batch_no, spu_list)
            # 发起分页
            if cur_page == 1:
                # 解析页面
                total_pages = parse_spu_total_page(response)
                self.logger.info("清单1: cat=%s, total_page=%s" % (catalog3Id, total_pages))
                for page in range(2, total_pages + 1):
                    yield self._build_list_req(self.sku_list_url, catalog3Id, page)
        else:
            self.logger.info('空页: cat=%s, page=%s' % (catalog3Id, cur_page))
